<template>
  <div class="add-movie-container">
    <h1 class="title">{{ isEditing ? '编辑商品' : '添加商品' }}</h1>
    
    <form class="add-movie-form" @submit.prevent="submitForm">
      <div class="form-group">
        <label for="title">商品标题</label>
        <input 
          type="text" 
          id="title" 
          v-model="movieData.title" 
          required
        />
        <p class="error" v-if="errors.title">{{ errors.title }}</p>
      </div>
      <div class="form-group">
        <label for="price">商品价格</label>
        <input 
          type="number" 
          id="price" 
          v-model="movieData.price" 
          required
        />
        <p class="error" v-if="errors.title">{{ errors.title }}</p>
      </div>
      <div class="form-group">
        <label for="description">描述</label>
        <textarea 
          id="description" 
          v-model="movieData.desc" 
          rows="4"
          required
        ></textarea>
        <p class="error" v-if="errors.description">{{ errors.description }}</p>
      </div>
      

      
      <div class="form-group">
        <label for="poster">商品图片URL</label>
        <input 
          type="text" 
          id="poster" 
          v-model="movieData.picPaths"
          placeholder="暂时只支持线上链接"
        />
      </div>
      
      
      <div class="form-actions">
        <button type="submit" class="submit-btn">{{ isEditing ? '更新商品' : '添加商品' }}</button>
        <button type="button" class="cancel-btn" @click="cancel">取消</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useMovieStore } from '@/stores/movie';
import { useCategoryStore } from '@/stores/category';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';

const movieStore = useMovieStore();
const categoryStore = useCategoryStore();
const route = useRoute();
const router = useRouter();
const categories = ref([]);
const errors = ref({});
const loading = ref(false);
const store = useUserStore()

const isEditing = ref(false);
const movieData = ref({
  title: '',
  desc: '',
  picPaths: '',
  price: '',
  userId:store.getUserId
});

const fetchCategories = async () => {
  try {
    categories.value = await categoryStore.fetchCategories();
  } catch (error) {
    console.error('获取分类失败:', error);
  }
};

const fetchMovie = async () => {
  if (route.params.id) {
    try {
      const movie = await movieStore.getMovie(route.params.id);
      movieData.value = {
        title: movie.title,
        desc: movie.description,
        actors: movie.director,
        picPaths: movie.posterUrl,
        price:movie.price,
      };
      isEditing.value = true;
    } catch (error) {
      console.error('获取商品失败:', error);
      router.push('/');
    }
  }
};

const validateForm = () => {
  if (!movieData.value.title){alert('标题不能为空')};
  if (!movieData.value.desc){alert('描述不能为空')};
  if (!movieData.value.price){alert('商品价格不能为空')};
  return 'false'
};

const submitForm = async () => {

  if (!validateForm()) return;
  loading.value = true;
  try {
    let response;
    if (isEditing.value) {
      response = await movieStore.updateMovie(route.params.id, movieData.value);
    } else {
      response = await movieStore.addMovie(movieData.value);
    }
    router.push(`/movie/${response.id}`);
  } catch (error) {
    alert("标题重复,请换个标题")
    console.error('操作失败:', error);
  } finally {
    loading.value = false;
  }
};

const cancel = () => {
  router.push('/');
};

onMounted(async () => {
  await fetchCategories();
  if (route.params.id) await fetchMovie();
});

watch(
  () => route.params.id,
  fetchMovie
);
</script>

<style scoped>
/* 保持原有样式并添加错误提示样式 */
.add-movie-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.add-movie-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-weight: bold;
  margin-bottom: 5px;
}

.form-group input,
.form-group textarea,
.form-group select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group .error {
  color: #e94560;
  font-size: 12px;
  margin-top: 3px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.submit-btn {
  flex: 1;
  padding: 10px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  flex: 1;
  padding: 10px;
  background-color: #f0f2f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}
</style>